'use strict';
const theme = require('./package.json').theme;
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const pkg = require('./package.json');

const isProd = process.env.NODE_ENV === 'production';
const minPostfix = isProd ? '.min' : '';
const minify = isProd ? 'minimize' : '';
const hash = '[hash:7]';
const bundleConfig = require("./permanent/bundle-config.json")
const entry = [
    './app/js/entry.js'
];
const devEntry = [
    'webpack/hot/dev-server',
    'webpack-hot-middleware/client?reload=true',
    './app/js/entry.js',
];
const basePlugins = [
    new webpack.DefinePlugin({
        'process.env': {
            'NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
        }
    }),
    new HTMLWebpackPlugin({
        url: isProd ? `<script src='https://dizhu-wechat-shop.oss-cn-beijing.aliyuncs.com/${pkg.name}/permanent/${bundleConfig.permanent.js}'></script>` : null,
        template: 'app/index.html',
        inject: true,
        prod: isProd,
        minify: isProd ? {
            removeComments: true,
            collapseWhitespace: true
        } : null,
    })
];
const envPlugins = isProd ? [
    new BundleAnalyzerPlugin(),
    new webpack.DllReferencePlugin({
        context: __dirname,
        manifest: require('./permanent/permanent-manifest.json')
    }),
    new ExtractTextPlugin({
        filename: `css/style.${hash}${minPostfix}.css`,
        disable: false,
        allChunks: true
    }),
    new webpack.optimize.UglifyJsPlugin({
        compress: {
            warnings: false
        }
    }),
    new webpack.BannerPlugin(`build: ${new Date().toString()}`),
    new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor',
        minChunks: function (module, count) {
            return (
                module.resource &&
                /\.js$/.test(module.resource) &&
                module.resource.indexOf(
                    path.join(__dirname, '../node_modules')
                ) === 0
            )
        }
    }),
    new webpack.optimize.AggressiveSplittingPlugin({
        minSize: 30000,
        maxSize: 50000,
        chunkOverhead: 0,
        entryChunkMultiplicator: 1,
    }),
    new webpack.optimize.CommonsChunkPlugin({
        name: 'manifest',
        chunks: ['vendor']
    })
] : [
    new webpack.HotModuleReplacementPlugin(),
];

let formatDate = {
    format: (time) => {
        let da = new Date();
        let year = da.getFullYear().toString() + '-';
        let month = (da.getMonth() + 1).toString() + '-';
        let date = (da.getDate()).toString() + '-';
        return (year + month + date + da.getHours());
    }
}

module.exports = {

    devtool: isProd ? 'source-map' : false,

    entry: isProd ? entry : devEntry,

    output: {
        path: isProd ? path.join(__dirname, `dist-${formatDate.format()}-${hash}`) : path.join(__dirname, 'dist'),
        filename: `js/[name].${hash}${minPostfix}.js`,
        publicPath: isProd ? `https://dizhu-wechat-shop.oss-cn-beijing.aliyuncs.com/${pkg.name}/dist-${formatDate.format()}-${hash}/` : '/',
        chunkFilename: `js/[name].${hash}${minPostfix}.js`,
        sourceMapFilename: "map/[name].js.map",
    },

    resolve: {
        modules: ['node_modules', path.join(__dirname, '../node_modules')],
        extensions: ['*', '.jsx', '.js', '.json', '.scss'],
        alias: {
            '_public_': '../Public/Api/Public.js',
            '_images_': '../../images',
            '_font_': '../../fonts'
        }
    },

    module: {
        rules: [
            {
                test: /\.jsx?$/,
                loaders: [
                    'babel-loader'
                ],
                include: [
                    path.join(__dirname, 'app/js'),
                ]
            },
            {
                test: /\.less$/,
                use: [
                    'style-loader',
                    'css-loader',
                    {loader: 'less-loader', options: {modifyVars: theme}},
                ],
                include: /node_modules/,
            },
            {
                test: /\.(css|scss|sass)$/,
                loaders: isProd ? ExtractTextPlugin.extract(
                    {
                        fallback: 'style-loader',
                        use: `css-loader?${minify}!postcss-loader!sass-loader`
                    }
                ) : 'style-loader!css-loader?sourceMap!postcss-loader!sass-loader?sourceMap: true'
            },
            {
                test: /\.jpe?g$|\.gif$|\.png|\.ico$/,
                use: [{
                    loader: 'url-loader',
                    options: {
                        name: 'images/[hash:8].[name].[ext]',
                        limit: '8192'
                    }
                }]
            },
            {
                test: /\.(eot|woff|svg|ttf|woff2|gif|appcache)(\?|$)/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: 'images/[hash:8].[name].[ext]'
                    }
                }],
            }

        ]
    },
    plugins: basePlugins.concat(envPlugins)

};
